package com.dycn.posdashboard.action;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.dycn.posdashboard.data.JsonResponseData;
import com.dycn.posdashboard.data.LiveUpTransactionInfo;
import com.dycn.posdashboard.data.PaginatedInfor;
import com.dycn.posdashboard.data.PosTransactionData;
import com.dycn.posdashboard.data.ServicesResultObject;
import com.dycn.posdashboard.dbhelper.DataBaseUser;
import com.dycn.posdashboard.listener.SystemInitListener;
import com.dycn.posdashboard.services.LiveTransactionDataServices;
import com.dycn.posdashboard.services.PosTradeServices;
import com.dycn.posdashboard.util.JSONObjectHelp;
import com.opensymphony.xwork2.ActionSupport;

public class LiveTransactionAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = -6176708885358239059L;
	protected final Log log = LogFactory.getLog(getClass());
    
	private LiveTransactionDataServices liveTransactionDataServices;
	private PosTradeServices posTradeServices;
    private JsonResponseData<Object> commonResponseDataJson;
	
    
	public PosTradeServices getPosTradeServices() {
		return posTradeServices;
	}


	public void setPosTradeServices(PosTradeServices posTradeServices) {
		this.posTradeServices = posTradeServices;
	}


	public LiveTransactionDataServices getLiveTransactionDataServices() {
		return liveTransactionDataServices;
	}


	public void setLiveTransactionDataServices(
			LiveTransactionDataServices liveTransactionDataServices) {
		this.liveTransactionDataServices = liveTransactionDataServices;
	}


	public JsonResponseData<Object> getCommonResponseDataJson() {
		return commonResponseDataJson;
	}


	public void setCommonResponseDataJson(
			JsonResponseData<Object> commonResponseDataJson) {
		this.commonResponseDataJson = commonResponseDataJson;
	}


	public String createTestLiveTransactionInfor(){
		List<PosTransactionData> newPosTransactionDataList=new ArrayList<PosTransactionData>();
    	HttpServletRequest request = ServletActionContext.getRequest();  
    	String branchNo=request.getParameter("branchNo");//分公司编号
    	String terminalMerchantNo=request.getParameter("terNo");//终端商户编号
    	log.info("branchNo:"+branchNo);
    	log.info("terminalMerchantNo:"+terminalMerchantNo);
    	if(branchNo!=null&&terminalMerchantNo!=null){
        	for(int i=0;i<50;i++){
        		PosTransactionData somePosTransactionData=new PosTransactionData();
        		somePosTransactionData.setBranchNo(branchNo);
        		somePosTransactionData.setTerminalBatchNo(terminalMerchantNo);
        		somePosTransactionData.setTradeMoney(Math.random()*1000);
        		somePosTransactionData.setTradeDate(DateUtils.addMinutes(new Date(), 1));
        		log.info("somePosTransactionData.getTradeDate():"+somePosTransactionData.getTradeDate());
        		newPosTransactionDataList.add(somePosTransactionData);
        	}
        	
    		liveTransactionDataServices.updateLastPosTransactionInforOnCache(newPosTransactionDataList);
    	}

		return SUCCESS;
	}
	
	/**
	 * 获取指定时间范围之内（2分钟之内）以秒为统计单位的订单数量及交易金额信息列表
	 * @return
	 */
	public String getLiveInscreamTransactionInfo2(){
		commonResponseDataJson=new JsonResponseData<Object>();
		commonResponseDataJson.setSuccess(false);
		commonResponseDataJson.setResultCode(JsonResponseData.SUCCESS);
		commonResponseDataJson.setMsg("参数提交错误~~~!!!!!!");
		commonResponseDataJson.setData(null);
    	HttpServletRequest request = ServletActionContext.getRequest();  
    	String branchNo=request.getParameter("branchNo");//分公司编号
    	String terminalMerchantNo=request.getParameter("terNo");//终端商户编号
       	String lastUpdateTimeStr=request.getParameter("lastUpdateTime");//
    	log.info("branchNo:"+branchNo);
    	
    	try{
        	Date lastUpdateCheckStartTime=null;
        	Date lastUpdateCheckEndTime=new Date();
//        	if(liveCheckSTimeStr!=null&&!liveCheckSTimeStr.trim().equals("")){
//    	    	SimpleDateFormat myFmt=new SimpleDateFormat("yyyyMMddHHmmss");
//    	    	log.info("lastUpdateTimeStr:"+liveCheckSTimeStr);
//    			try {
//    				lastUpdateCheckStartTime=myFmt.parse(liveCheckSTimeStr);
//    			} catch (ParseException e) {
//    				// TODO Auto-generated catch block
//    				e.printStackTrace();
//    			}
//        	}

			if(lastUpdateCheckStartTime==null){
				lastUpdateCheckStartTime=DateUtils.addMinutes(lastUpdateCheckEndTime,-2);//2分钟之前
			}
			
			//lastUpdateCheckEndTime=DateUtils.addSeconds(lastUpdateCheckStartTime, -30);
    
			//ServicesResultObject<List<LiveUpTransactionInfo>> servicesResultObjectOfgetLivePos=null;

			ServicesResultObject<List<LiveUpTransactionInfo>> servicesResultObjectOfgetLivePos=this.liveTransactionDataServices.getLiveIncrementPosTransactionInfor(DataBaseUser.MAIN_USER, branchNo,terminalMerchantNo,10*1000,lastUpdateCheckStartTime,lastUpdateCheckEndTime);
	    	
	    	if(!servicesResultObjectOfgetLivePos.isSuccess()){
        		commonResponseDataJson.setSuccess(servicesResultObjectOfgetLivePos.isSuccess());
           		commonResponseDataJson.setMsg(servicesResultObjectOfgetLivePos.getResultMsg());
        		commonResponseDataJson.setData(null);
        	}else{

        		commonResponseDataJson.setMsg("");
        		commonResponseDataJson.setSuccess(true);
        		commonResponseDataJson.setResultCode(JsonResponseData.SUCCESS);
        		commonResponseDataJson.setData(servicesResultObjectOfgetLivePos.getReturnObj());
        		
          		log.debug("getLiveInscreamTransactionInfo json data22:"+JSONObject.fromObject(commonResponseDataJson,JSONObjectHelp.getJsonConfig()).toString());

        	}
    	}catch(Exception exp){
    		exp.printStackTrace();
    		commonResponseDataJson.setResultCode(JsonResponseData.EXCEPTION);
    		commonResponseDataJson.setMsg(commonResponseDataJson.getMsg()+exp);
    	}
		
		return SUCCESS;
	}
	
	/**
	 * 从数据库中获取指定时间范围内(10分钟的交易)的数据
	 * 
	 * @return
	 */
	public String getLiveInscreamTransactionInfo3(){
		commonResponseDataJson=new JsonResponseData<Object>();
		commonResponseDataJson.setSuccess(false);
		commonResponseDataJson.setResultCode(JsonResponseData.SUCCESS);
		commonResponseDataJson.setMsg("参数提交错误~~~!!!!!!");
		commonResponseDataJson.setData(null);
    	HttpServletRequest request = ServletActionContext.getRequest();  
    	String branchNo=request.getParameter("branchNo");//分公司编号
    	String terminalMerchantNo=request.getParameter("terNo");//终端商户编号
    	String cardNo=request.getParameter("cardNo");//卡号
    	String limitstr=request.getParameter("limit");//每页记录数
    	
    	String lastUpdateTimeStr=request.getParameter("lastUpdateTime");
    	
    	try{
	    	int startPage=0;
	    	int statsDateRangeType=0;//0-》全部 1 ->本月 2->本年
	    	int pageSize=((limitstr==null||limitstr.trim().equals(""))?20:Integer.parseInt(limitstr));
	    	startPage=1;
			PaginatedInfor<PosTransactionData> nonDataPaginatedInfor=new PaginatedInfor<PosTransactionData>();
			nonDataPaginatedInfor.setPageId(startPage);
			nonDataPaginatedInfor.setPageRecords(pageSize);

			nonDataPaginatedInfor.setTotalRecords(20);
	
			Date lastUpdateCheckStartTime=null;
        	Date lastUpdateCheckEndTime=null;
        	if(lastUpdateTimeStr!=null&&!lastUpdateTimeStr.trim().equals("")){
    	    	SimpleDateFormat myFmt=new SimpleDateFormat("yyyyMMddHHmmss");
    	    	log.info("lastUpdateTimeStr:"+lastUpdateTimeStr);
    			try {
    				lastUpdateCheckStartTime=myFmt.parse(lastUpdateTimeStr);
    			} catch (ParseException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
        	}

//			if(lastUpdateCheckStartTime==null){
//				lastUpdateCheckStartTime=DateUtils.addMinutes(new Date(),0);
//			}

			ServicesResultObject<List<LiveUpTransactionInfo>> servicesResultObjectOfgetPosTransactionDataListBy=this.liveTransactionDataServices.getRecentLiveIncrementPosTransactionInfor(DataBaseUser.MAIN_USER,
					branchNo, terminalMerchantNo,cardNo,lastUpdateCheckStartTime,null);
			//以SystemInitListener.SYNC_POS_TRADE_QUARTZ为单位group数据
			
			
			
    	    if(!servicesResultObjectOfgetPosTransactionDataListBy.isSuccess()){
        		commonResponseDataJson.setSuccess(servicesResultObjectOfgetPosTransactionDataListBy.isSuccess());
           		commonResponseDataJson.setMsg(servicesResultObjectOfgetPosTransactionDataListBy.getResultMsg());
        		commonResponseDataJson.setData(null);
    	    }else{
    	    	
        		commonResponseDataJson.setMsg("");
        		commonResponseDataJson.setSuccess(true);
        		commonResponseDataJson.setResultCode(JsonResponseData.SUCCESS);
        		commonResponseDataJson.setData(servicesResultObjectOfgetPosTransactionDataListBy.getReturnObj());
    	    	
    	    	log.debug("getLiveInscreamTransactionInfo3:"+JSONObject.fromObject(commonResponseDataJson,JSONObjectHelp.getJsonConfig()).toString());
    	    	//
    	    }
//        	}else{
//        		PaginatedInfor<PosTransactionData> posTransactionDataPageInfor=servicesResultObjectOfgetPosTransactionDataListBy.getReturnObj();
//         		  
//        		List<PosTransactionData> currrentPagePosTransactionDataList=posTransactionDataPageInfor.getDataList();
//        		int totalRecords=posTransactionDataPageInfor.getTotalRecords();
//        		int totalPages=1;
//    			if(totalRecords%pageSize!=0){
//					totalPages=totalRecords/pageSize+1;
//				}else{
//					totalPages=totalRecords/pageSize;
//				}
//    			
//    			if(startPage>totalPages){
//    				startPage=totalPages;
//    			}
//    			
//        		commonResponseDataJson.setMsg("");
//        		commonResponseDataJson.setSuccess(true);
//        		commonResponseDataJson.setResultCode(JsonResponseData.SUCCESS);
//        		commonResponseDataJson.setData(currrentPagePosTransactionDataList);
//        		
//        		commonResponseDataJson.setRecordsPer(pageSize);
//        		commonResponseDataJson.setPageId(startPage);
//        		commonResponseDataJson.setTotalRecords(totalRecords);
//        		commonResponseDataJson.setTotalPage(totalPages);
//        		
//          		log.debug("getETLJobEfforts json data22:"+JSONObject.fromObject(commonResponseDataJson,JSONObjectHelp.getJsonConfig()).toString());
//
//        	}
    		
    		
    	}catch(Exception exp){
    		exp.printStackTrace();
    		commonResponseDataJson.setResultCode(JsonResponseData.EXCEPTION);
    		commonResponseDataJson.setMsg(commonResponseDataJson.getMsg()+exp);
    	}
		
		return SUCCESS;
	}
	
	/**
	 * 
	 * @return
	 */
	public String getLiveInscreamTransactionInfo(){
		
		commonResponseDataJson=new JsonResponseData<Object>();
		commonResponseDataJson.setSuccess(false);
		commonResponseDataJson.setResultCode(JsonResponseData.SUCCESS);
		commonResponseDataJson.setMsg("参数提交错误~~~!!!!!!");
		commonResponseDataJson.setData(null);
    	HttpServletRequest request = ServletActionContext.getRequest();  
    	String branchNo=request.getParameter("branchNo");//分公司编号
    	String terminalMerchantNo=request.getParameter("terNo");//终端商户编号
    	String lastUpdateTimeStr=request.getParameter("lastUpdateTime");//终端商户编号
    	
    	log.info("branchNo:"+branchNo);
    	
    	try{
        	Date lastUpdateCheckStartTime=null;
        	Date lastUpdateCheckEndTime=null;
        	if(lastUpdateTimeStr!=null&&!lastUpdateTimeStr.trim().equals("")){
    	    	SimpleDateFormat myFmt=new SimpleDateFormat("yyyyMMddHHmmss");
    	    	log.info("lastUpdateTimeStr:"+lastUpdateTimeStr);
    			try {
    				lastUpdateCheckStartTime=myFmt.parse(lastUpdateTimeStr);
    			} catch (ParseException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
        	}

			if(lastUpdateCheckStartTime==null){
				lastUpdateCheckStartTime=DateUtils.addMinutes(new Date(),0);
			}
			
			//lastUpdateCheckEndTime=DateUtils.addSeconds(lastUpdateCheckStartTime, -30);
    
			ServicesResultObject<List<LiveUpTransactionInfo>> servicesResultObjectOfgetLivePos=null;
	    	if(branchNo!=null&&!branchNo.trim().equals("")){
	    		servicesResultObjectOfgetLivePos=this.liveTransactionDataServices.getLivePosTransactionInforOfBranch(DataBaseUser.MAIN_USER, branchNo, lastUpdateCheckStartTime);
	    	}else if(terminalMerchantNo!=null&&!terminalMerchantNo.trim().equals("")){
	    		servicesResultObjectOfgetLivePos=this.liveTransactionDataServices.getLiveIncrementPosTransactionInforOfMerchant(DataBaseUser.MAIN_USER, terminalMerchantNo, lastUpdateCheckStartTime);
	    		
	    	}else{
	    		servicesResultObjectOfgetLivePos=this.liveTransactionDataServices.getLiveIncrementPosTransactionInfor(DataBaseUser.MAIN_USER,  lastUpdateCheckStartTime);
	    		
	    	}
	    	
	    	if(!servicesResultObjectOfgetLivePos.isSuccess()){
        		commonResponseDataJson.setSuccess(servicesResultObjectOfgetLivePos.isSuccess());
           		commonResponseDataJson.setMsg(servicesResultObjectOfgetLivePos.getResultMsg());
        		commonResponseDataJson.setData(null);
        	}else{

        		commonResponseDataJson.setMsg("");
        		commonResponseDataJson.setSuccess(true);
        		commonResponseDataJson.setResultCode(JsonResponseData.SUCCESS);
        		commonResponseDataJson.setData(servicesResultObjectOfgetLivePos.getReturnObj());
        		
          		log.debug("getLiveInscreamTransactionInfo json data22:"+JSONObject.fromObject(commonResponseDataJson,JSONObjectHelp.getJsonConfig()).toString());

        	}
    	}catch(Exception exp){
    		exp.printStackTrace();
    		commonResponseDataJson.setResultCode(JsonResponseData.EXCEPTION);
    		commonResponseDataJson.setMsg(commonResponseDataJson.getMsg()+exp);
    	}
		
		return SUCCESS;
	}
}
